var config = require('./config/config.json')
// var request = require('request')
const axios = require('axios');
var fs = require('fs');
var userId = '';
try {
    userId = fs.readFileSync('userId')
} catch (e) {
    console.log("userId文件不存在")
}
if (!userId) {
    userId = getUserId();
    fs.writeFileSync('userId', userId);
}

//   console.log(userId)
// console.log(config)

var fundlist = config.funds.flatMap(function (current) {

    return current.fund.map(function (item) {

        return item.code;
    });
});

var fundListM = Array.from(new Set(fundlist))

var fundSet = fundListM.join(",");


// console.log(fundSet)
let url =
    "https://fundmobapi.eastmoney.com/FundMNewApi/FundMNFInfo?pageIndex=1&pageSize=100&plat=Android&appType=ttjj&product=EFund&Version=1&deviceid=" +
    userId +
    "&Fcodes=" +
    fundSet;
axios
    .get(url)
    .then((res) => {
        let data = res.data.Datas;
        let dataList = [];

        data.forEach((val) => {
            let data = {
                fundcode: val.FCODE,
                name: val.SHORTNAME,
                jzrq: val.PDATE,
                dwjz: isNaN(val.NAV) ? null : val.NAV,
                gsz: isNaN(val.GSZ) ? null : val.GSZ,
                gszzl: isNaN(val.GSZZL) ? 0 : val.GSZZL,
                gztime: val.GZTIME,
            };
            if (val.PDATE != "--" && val.PDATE == val.GZTIME.substr(0, 10)) {
                data.gsz = val.NAV;
                data.gszzl = isNaN(val.NAVCHGRT) ? 0 : val.NAVCHGRT;
                data.hasReplace = true;
            }
            dataList.push(data);
        });
// console.log(dataList)
        config.funds.forEach(function (current) {

            var funds = current.fund;
            funds.forEach(function (fund) {
                let slt = dataList.filter((data) => fund.code == data.fundcode);
                Object.assign(fund, slt[0]);

                fund.amount = calculateMoney(fund);
                fund.gains = calculate(fund, fund.hasReplace);
                fund.costGains = calculateCost(fund);
                fund.costGainsRate = calculateCostRate(fund);
            })

        })
// console.log(JSON.stringify(config))

        var groupGains = [];
        groupGains = config.funds.map(function (current) {

            var groupGain = {};
            groupGain.group = current.group;
            groupGain.targetGains = current.targetGains
            var funds = current.fund;

            let allCostGains = 0;
            funds.forEach((val) => {
                allCostGains += parseFloat(val.costGains);
            });


            let allGains = 0;
            funds.forEach((val) => {
                allGains += parseFloat(val.gains);
            });
            let allTotalGains = 0;
            allTotalGains = parseFloat(allGains)+parseFloat(allCostGains);
            allGains = allGains.toFixed(2);
            allCostGains = allCostGains.toFixed(2);
            allTotalGains = allTotalGains.toFixed(2);
            groupGain.allGains = allGains;
            groupGain.allCostGains = allCostGains;
            groupGain.allTotalGains = allTotalGains;
            return groupGain;
        });
        var body = groupGains.map(function (item) {

            return "$"+item.group + "=>日收益:" + item.allGains + ",持有收益:" + item.allCostGains +",预估总收益:"+item.allTotalGains+ ",目标收益:" + item.targetGains;
        }).join("\n");

        var barkUrl = config.bark;
        const params = new URLSearchParams();
        params.append('body', body);
        axios.post(barkUrl, params)
            .then(function (response) {
                // handle success
                console.log(response.data);
            })
    })
    .catch((error) => {
    });


function getUserId() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (
        c
    ) {
        var r = (Math.random() * 16) | 0,
            v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}

function calculateMoney(val) {
    let sum = (val.dwjz * val.num).toFixed(2);
    return sum;
}

function calculate(val, hasReplace) {
    var sum = 0;
    let num = val.num ? val.num : 0;
    if (hasReplace) {
        sum = ((val.dwjz - val.dwjz / (1 + val.gszzl * 0.01)) * num).toFixed(2);
    } else {
        if (val.gsz) {
            sum = ((val.gsz - val.dwjz) * num).toFixed(2);
        }
    }
    return sum;
}

function calculateCost(val) {
    if (val.cost) {
        let sum = ((val.dwjz - val.cost) * val.num).toFixed(2);
        return sum;
    } else {
        return 0;
    }
}

function calculateCostRate(val) {
    if (val.cost && val.cost != 0) {
        let sum = (((val.dwjz - val.cost) / val.cost) * 100).toFixed(2);
        return sum;
    } else {
        return 0;
    }
}
